package com.cskaoyan.service.wxorder;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.bo.order.CommentBO;
import com.cskaoyan.model.bo.wxorder.WxOrderBO;
import com.cskaoyan.model.bo.wxorder.WxOrderIdBO;
import com.cskaoyan.model.vo.wxcart.WxCheckoutTotalVo;
import com.cskaoyan.model.vo.wxorder.HandleOption;
import com.cskaoyan.model.vo.wxorder.WxSubmitVO;
import com.cskaoyan.model.vo.wxorder.detail.DetailUserVO;
import com.cskaoyan.model.vo.wxorder.detail.DetailVO;
import com.cskaoyan.model.vo.wxorder.list.InnerGoods;
import com.cskaoyan.model.vo.wxorder.list.InnerOrderVO;
import com.cskaoyan.model.vo.wxorder.list.OrderListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @program: project-market
 * @description: wxOrder
 * @author: shiyue
 * @create: 2021/12/2 14:51
 **/
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MallOrderGoodsMapper orderGoodsMapper;

    @Autowired
    MallOrderMapper orderMapper;

    @Autowired
    MallCommentMapper commentMapper;

    @Autowired
    MallCartMapper cartMapper;

    @Autowired
    MallCouponUserMapper couponUserMapper;

    @Override
    public OrderListVO getlist(WxOrderBO bo) {
        OrderListVO list = new OrderListVO();

        PageHelper.startPage(bo.getPage(), bo.getLimit());
        //筛选
        MallOrderGoodsExample orderGoodsExample = new MallOrderGoodsExample();
        MallOrderExample orderExample = new MallOrderExample();

        MallOrderGoodsExample.Criteria orderGoodsExampleCriteria = orderGoodsExample.createCriteria();
        MallOrderExample.Criteria orderExampleCriteria = orderExample.createCriteria();


        if (bo.getShowType() == 0) {
            orderExampleCriteria.andOrderStatusIsNotNull();
        } else if (bo.getShowType() == 1) {//待付款对应101
            orderExampleCriteria.andOrderStatusEqualTo((short) 101);
        } else if (bo.getShowType() == 2) {//待发货对应201
            orderExampleCriteria.andOrderStatusEqualTo((short) 201);
        } else if (bo.getShowType() == 3) {//待收货对应301
            orderExampleCriteria.andOrderStatusEqualTo((short) 301);
        } else if (bo.getShowType() == 4) {
            //待评价对应401或402,且要查表market_order中的comments值大于0才能待评价
            //每评价一次要把market_order里的comments减1,更稳的判断是把该order对应goods所有comment相加不大于0
            orderExampleCriteria.andOrderStatusBetween((short) 400, (short) 403);
            orderExampleCriteria.andCommentsGreaterThan((short) 0);
        }

        List<MallOrder> mallOrders = orderMapper.selectByExample(orderExample);
        List<InnerOrderVO> innerOrderVOS = new ArrayList<InnerOrderVO>();

        for (MallOrder mallOrder : mallOrders) {
            int id = mallOrder.getId();
            List<InnerGoods> innerGoods = orderGoodsMapper.selectById(id);//拿到当前order的所有商品
            InnerOrderVO innerOrderVO = new InnerOrderVO();//构造InnerOrderVO
            innerOrderVO.setOrderStatusText(mallOrder.getOrderStatus());
            innerOrderVO.setAftersaleStatus(mallOrder.getAftersaleStatus());
            innerOrderVO.setIsGroupin(false);
            innerOrderVO.setOrderSn(mallOrder.getOrderSn());
            innerOrderVO.setActualPrice(mallOrder.getActualPrice());
            innerOrderVO.setInnerGoods(innerGoods);//list,handle用查出的状态码
            innerOrderVO.setId(mallOrder.getId());
            innerOrderVO.setHandleOption(mallOrder.getOrderStatus());
            innerOrderVOS.add(innerOrderVO);
        }

        //构造OrderListVO

        PageInfo pageInfo = new PageInfo(innerOrderVOS);
        Integer total = Math.toIntExact(pageInfo.getTotal());
        return new OrderListVO(total, bo.getLimit(), bo.getPage(), innerOrderVOS);

    }

    @Override
    public DetailVO getDetail(Integer orderId) {
        MallOrderExample orderExample = new MallOrderExample();
        MallOrderExample.Criteria orderExampleCriteria = orderExample.createCriteria();
        orderExampleCriteria.andIdEqualTo(orderId);

        List<MallOrder> list = orderMapper.selectByExample(orderExample);


        MallOrder mallOrder = list.get(0);
        DetailUserVO detailUserVO = new DetailUserVO();
        detailUserVO.setConsignee(mallOrder.getConsignee());
        detailUserVO.setAddress(mallOrder.getAddress());
        detailUserVO.setAddTime(mallOrder.getAddTime());
        detailUserVO.setOrderSn(mallOrder.getOrderSn());
        detailUserVO.setActualPrice(mallOrder.getActualPrice());
        detailUserVO.setMobile(mallOrder.getMobile());
        detailUserVO.setMessage(mallOrder.getMessage());
        detailUserVO.setOrderStatusText(mallOrder.getOrderStatus());
        detailUserVO.setAftersaleStatus(mallOrder.getAftersaleStatus());
        detailUserVO.setGoodsPrice(mallOrder.getGoodsPrice());
        detailUserVO.setCouponPrice(mallOrder.getCouponPrice());
        detailUserVO.setId(mallOrder.getId());
        detailUserVO.setFreightPrice(mallOrder.getFreightPrice());

        HandleOption handleOption = new HandleOption(mallOrder.getOrderStatus());
        detailUserVO.setHandleOption(handleOption);

        MallOrderGoodsExample orderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria orderGoodsExampleCriteria = orderGoodsExample.createCriteria();
        orderGoodsExampleCriteria.andOrderIdEqualTo(orderId);
        List<MallOrderGoods> mallOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);


        // List<MallOrderGoods> mallOrderGoods=new ArrayList<>();

        return new DetailVO(detailUserVO, mallOrderGoods);
    }

    @Override
    public int cancel(WxOrderIdBO bo) {

/*        MallOrderExample orderExample = new MallOrderExample();
        MallOrderExample.Criteria orderExampleCriteria = orderExample.createCriteria();
        orderExampleCriteria.andIdEqualTo(orderId);
        int row2= orderGoodsMapper.updateByExampleSelective()ByExample(orderExample);*/
        Integer orderId = bo.getOrderId();
        int row = orderMapper.updateToCancel(orderId);
        return row;
    }

    @Override
    public int deleteOrder(WxOrderIdBO bo) {
        Integer orderId = bo.getOrderId();
        int row1 = orderMapper.deleteByPrimaryKey(orderId);
        MallOrderGoodsExample orderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria orderExampleCriteria = orderGoodsExample.createCriteria();
        orderExampleCriteria.andIdEqualTo(orderId);
        int row2 = orderGoodsMapper.deleteByExample(orderGoodsExample);
        return row2;
    }

    @Override
    public int confirmOrder(WxOrderIdBO bo) {
        Integer orderId = bo.getOrderId();
        int row = orderMapper.updateToConfirm(orderId);
        return row;
    }

    @Override
    public int refundOrder(WxOrderIdBO bo) {
        Integer orderId = bo.getOrderId();
        int row = orderMapper.updateToRefund(orderId);
        return row;
    }

    @Override
    public MallOrderGoods goodsWhenComment(Integer orderId, Integer goodsId) {
        MallOrderGoodsExample orderGoodsExample = new MallOrderGoodsExample();
        MallOrderGoodsExample.Criteria orderExampleCriteria = orderGoodsExample.createCriteria();
        orderExampleCriteria.andOrderIdEqualTo(orderId);
        orderExampleCriteria.andGoodsIdEqualTo(goodsId);
        List<MallOrderGoods> list = orderGoodsMapper.selectByExample(orderGoodsExample);
        return list.get(0);
    }

    @Override
    public int commentOrder(CommentBO commentBO) {
        MallOrderGoods mallOrderGoods = orderGoodsMapper.selectByPrimaryKey(commentBO.getOrderGoodsId());
        int orderId = mallOrderGoods.getOrderId();
        int goodsId = mallOrderGoods.getGoodsId();
        MallOrder mallOrder = orderMapper.selectByPrimaryKey(orderId);
        int userId = mallOrder.getUserId();
        MallCommentWx mallComment = new MallCommentWx();
        byte a = 0;
        String[] PicUrls = commentBO.getPicUrls().toArray(new String[commentBO.getPicUrls().size()]);
        mallComment.setValueId(goodsId);
        mallComment.setType(a);
        mallComment.setContent(commentBO.getContent());
        mallComment.setAdminContent("");
        mallComment.setUserId(userId);
        mallComment.setHasPicture(commentBO.isHasPicture());
        mallComment.setPicUrls(PicUrls);
        mallComment.setStar(commentBO.getStar());
        mallComment.setAddTime(new Date());
        mallComment.setUpdateTime(new Date());
        mallComment.setDeleted(false);
        int row = commentMapper.insertMallCommentWx(mallComment);
        Integer commentId = mallComment.getId();
        //还要向market_order_goods中更新comment值为上面取回的这个id
        Integer id = commentBO.getOrderGoodsId();
        int row1 = orderGoodsMapper.updateComment(id, commentId);

        //为判断订单是否出现在待评价,每评价一次要把market_order里的comments减1(或乘以number,暂时不清楚),
        // 更稳的是判断该order对应的market_order_goods表中所有comment相加是否不大于0
        int row2 = orderMapper.updateComments(orderId);
        return 0;
    }

    @Override
    public WxSubmitVO submitOrder(WxCheckoutTotalVo vo, String msg) {
      /*  需要操作的表 cart 逻辑删除
         coupon_user 如果vo中coupon_id!=-1,则coupon_user表中更新status为1
         order,order_goods  插入订单*/

        List<MallCart> checkedGoodsList = vo.getCheckedGoodsList();



        //更新优惠券使用状态
        if (vo.getCouponId() != -1) {
            int userCouponId = vo.getUserCouponId();
            MallCouponUser record = couponUserMapper.selectByPrimaryKey(userCouponId);
            record.setCouponId(1);
            couponUserMapper.updateByPrimaryKeySelective(record);
        }


        //向order表插入数据
        MallOrder mallOrder = new MallOrder();
        MallAddress checkedAddress = vo.getCheckedAddress();
        System.out.println(checkedAddress);
        mallOrder.setUserId(checkedAddress.getUserId());
        //取一个新order_sn
        String maxOrder_sn = orderMapper.selectMaxOrderSn();
        int a = Integer.parseInt(maxOrder_sn);


        Date now = new Date(); // 创建一个Date对象，获取当前时间
        // 指定格式化格式
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmss"); // 将当前时间袼式化为指定的格式
       // System.out.println(f.format(now));
        String sdate=f.format(now);

        int max=999999,min=100000;
        int ran2 = (int) (Math.random()*(max-min)+min);
        String attachString=Integer.toString(ran2);
        String newMaxOrder_sn = sdate+ran2;
        System.out.println(newMaxOrder_sn);

        mallOrder.setAddress(checkedAddress.getAddressDetail());
        mallOrder.setOrderSn(newMaxOrder_sn);
        mallOrder.setOrderStatus((short) 101);
        mallOrder.setAftersaleStatus((short) 0);
        mallOrder.setConsignee(checkedAddress.getName());
        mallOrder.setMobile(checkedAddress.getTel());
        mallOrder.setMessage(msg);
        mallOrder.setGoodsPrice(vo.getGoodsTotalPrice());
        mallOrder.setFreightPrice(vo.getFreightPrice());
        mallOrder.setCouponPrice(vo.getCouponPrice());
        mallOrder.setIntegralPrice((BigDecimal.valueOf(0)));
        mallOrder.setGrouponPrice((BigDecimal.valueOf(0)));

        BigDecimal orderPrice = mallOrder.getGoodsPrice();
        orderPrice = orderPrice.add(mallOrder.getFreightPrice());
        orderPrice = orderPrice.subtract(mallOrder.getCouponPrice());
        mallOrder.setOrderPrice(orderPrice);

        BigDecimal actualPrice = orderPrice.subtract(mallOrder.getIntegralPrice());
        mallOrder.setActualPrice(actualPrice);
        mallOrder.setComments((short) vo.getCheckedGoodsList().size());//一种商品一次评价机会
        mallOrder.setAddTime(new Date());
        mallOrder.setUpdateTime(new Date());
        mallOrder.setDeleted(false);

        int row = orderMapper.insertSelective(mallOrder);//注意要修改使其能取回主键
        Integer orderid = mallOrder.getId();//取回主键


        //向ordergoods表中插入数据;
        for (MallCart mallCart : checkedGoodsList) {
            MallOrderGoods mallOrderGoods = new MallOrderGoods();
            mallOrderGoods.setOrderId(orderid);
            mallOrderGoods.setGoodsId(mallCart.getGoodsId());
            mallOrderGoods.setGoodsName(mallCart.getGoodsName());
            mallOrderGoods.setGoodsSn(mallCart.getGoodsSn());
            mallOrderGoods.setProductId(mallCart.getProductId());
            mallOrderGoods.setNumber((int)mallCart.getNumber());
            mallOrderGoods.setPrice(mallCart.getPrice());
            mallOrderGoods.setSpecifications(mallCart.getSpecifications());
            mallOrderGoods.setPicUrl(mallCart.getPicUrl());
            mallOrderGoods.setAddTime(new Date());
            mallOrderGoods.setUpdateTime(new Date());
            mallOrderGoods.setDeleted(false);
            int row1=orderGoodsMapper.insertSelective(mallOrderGoods);
        }

        WxSubmitVO wxSubmitVO = new WxSubmitVO();
        wxSubmitVO.setOrderId(orderid);
        wxSubmitVO.setGrouponLinkId(0);
        System.out.println(orderid);
        System.out.println(wxSubmitVO.toString());;
        //遍历    查出购物商品id,执行购物车的逻辑删除
        for (MallCart mallCart : checkedGoodsList) {
            Integer id = mallCart.getId();
            MallCart record = cartMapper.selectByPrimaryKey(id);
            record.setDeleted(true);
            cartMapper.updateByPrimaryKeySelective(record);
        }
        return wxSubmitVO;
    }
}



